package com.note.app.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.note.common.domain.NoteTag;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 笔记标签关联Mapper
 */
@Mapper
public interface NoteTagMapper extends BaseMapper<NoteTag> {

    /**
     * 批量插入笔记标签关系
     *
     * @param noteId 笔记ID
     * @param tagIds 标签ID列表
     * @return 影响行数
     */
    default int batchInsert(Long noteId, List<Long> tagIds) {
        int count = 0;
        for (Long tagId : tagIds) {
            NoteTag noteTag = new NoteTag();
            noteTag.setNoteId(noteId);
            noteTag.setTagId(tagId);
            count += this.insert(noteTag);
        }
        return count;
    }

    /**
     * 查询笔记关联的所有标签ID
     *
     * @param noteId 笔记ID
     * @return 标签ID列表
     */
    @Select("SELECT tag_id FROM note_tag WHERE note_id = #{noteId} AND deleted = 0")
    List<Long> selectTagIdsByNoteId(@Param("noteId") Long noteId);

    /**
     * 查询使用该标签的笔记数量
     *
     * @param tagId 标签ID
     * @return 笔记数量
     */
    @Select("SELECT COUNT(*) FROM note_tag WHERE tag_id = #{tagId} AND deleted = 0")
    int countNotesByTagId(@Param("tagId") Long tagId);

    /**
     * 物理删除笔记的所有标签关联
     *
     * @param noteId 笔记ID
     * @return 影响行数
     */
    @Delete("DELETE FROM note_tag WHERE note_id = #{noteId}")
    int deleteByNoteId(@Param("noteId") Long noteId);
} 